<?php
/**
 * CreateTime: 2023/11/22 16:42
 * User:LinQ
 */

namespace App\Http\Middleware;
use App\Func\User\UserFunc;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class cPermissionMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        $controller = $request->route()->getControllerClass();
        $method = $request->route()->getActionMethod();
        // 白名单过滤 存在于白名单直接过滤
        $whitelist = config('login_whitelist');
        if(isset($whitelist[$controller])){
            $whitelistCanMethod = $whitelist[$controller];
        }else{
            $whitelistCanMethod = [];
        }
        if(in_array($method,$whitelistCanMethod)){
            return $next($request);
        }
        $userFunc = new UserFunc();
        // 登录校验
        $userFunc->getLoginInfo();
        $permissionsConfig = config('permissions');
        if(isset($permissionsConfig[$controller])){
            $methodCanAuth = $permissionsConfig[$controller];
            // 若查询到存在配置表则判断权限 否则直接放行
            if(isset($methodCanAuth[$method])){
                $canAuth = $userFunc->canAuths($methodCanAuth[$method]['auth_code'],$methodCanAuth[$method]['auth_value']);
                if(!$canAuth){
                    s_fail_return(null,
                        trans('message.not_has_auth'),
                        false,
                        code:'Forbidden',
                        httpCode: 403
                    );
                }
            }
        }
        return $next($request);
    }
}